package com.shop.user.api.service.impl;

import com.shop.common.entity.user.UserBase;
import com.shop.common.entity.user.UserPay;
import com.shop.common.model.ServiceBean;
import com.shop.common.model.param.user.UserBaseInput;
import com.shop.common.model.param.user.UserPayInput;
import com.shop.common.model.result.user.UserBaseOutput;
import com.shop.common.tmpl.BaseService;
import com.shop.common.util.RedisUtil;
import com.shop.common.util.SendCodeUtil;
import com.shop.common.util.state.KeyPrefix;
import com.shop.common.util.state.UserState;
import com.shop.user.api.model.RestModel;
import com.shop.user.api.service.IUserSvc;
import com.shop.user.atom.atomsvc.IUserAtomSvc;
import com.shop.user.atom.atomsvc.IUserPayAtomSvc;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description:
 *
 * @author zhoulk
 * @date: 2019年03月27日  21:46
 */
@Service
public class UserSvc extends BaseService implements IUserSvc {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserSvc.class);

    @Autowired
    IUserAtomSvc userAtomSvc;
    @Autowired
    IUserPayAtomSvc userPayAtomSvc;
    @Autowired
    RedisUtil redisUtil;

    @Override
    public ServiceBean restPwd(RestModel restModel) {
        UserBase userBase = userAtomSvc.selectBaseUserById(restModel.getUserId());
        String oldPwd = DigestUtils.md5Hex(restModel.getOld());
        String newPwd = DigestUtils.md5Hex(restModel.getNow());
        if (!userBase.getPassword().equals(oldPwd)) {
            return resultFailed("原密码错误，请重试");
        }
        UserBaseInput userBaseInput = new UserBaseInput();
        userBaseInput.setUserId(userBase.getUserId());
        userBaseInput.setPassword(newPwd);
        return userAtomSvc.updateBaseUser(userBaseInput);
    }

    @Override
    public ServiceBean restPayPwd(RestModel restModel) {
        UserPay userPay = userPayAtomSvc.selectUserPay(restModel.getUserId()).getData();
        String oldPwd = DigestUtils.md5Hex(restModel.getOld());
        String newPwd = DigestUtils.md5Hex(restModel.getNow());
        UserPayInput userPayInput = new UserPayInput();
        if (StringUtils.isBlank(userPay.getPayPwd())  || userPay.getPayPwd().equals(oldPwd)) {
            userPayInput.setId(userPay.getId());
            userPayInput.setPayPwd(newPwd);
            return userPayAtomSvc.updateUserPay(userPayInput);
        }
        return resultFailed("旧密码错误");
    }

    @Override
    public ServiceBean restPhone(RestModel restModel) {
        String oldPhone = restModel.getOld();
        String oldVerify = restModel.getOldVerify();
        String nowPhone = restModel.getNow();
        String nowVerify = restModel.getNowVerify();
        Integer userId = restModel.getUserId();
        UserBase userBase = userAtomSvc.selectBaseUserById(userId);
        if (StringUtils.isBlank(userBase.getPhone()) && !userBase.getPhone().equals(oldPhone)) {
            return resultFailed("原手机号与系统记录不匹配，请刷新页面后重试");
        }
        if (oldPhone.equals(nowPhone)) {
            return resultFailed("新手机号与原手机号相同，不用修改");
        }
        if (StringUtils.isBlank(oldPhone) || SendCodeUtil.VALIDATE_CODE(KeyPrefix.REST, oldPhone, oldVerify)) {
            if (!SendCodeUtil.VALIDATE_CODE(KeyPrefix.REST, nowPhone, nowVerify)) {
                return resultFailed("新手机号验证码错误");
            }
        } else {
            return resultFailed("原手机号验证码错误");
        }
        UserBaseInput userBaseInput = new UserBaseInput();
        userBaseInput.setUserId(userId);
        userBaseInput.setPhone(nowPhone);
        return userAtomSvc.updateBaseUser(userBaseInput);
    }

    @Override
    public ServiceBean restEmail(RestModel restModel) {
        String oldEmail = restModel.getOld();
        String oldVerify = restModel.getOldVerify();
        String nowEmail = restModel.getNow();
        String nowVerify = restModel.getNowVerify();
        Integer userId = restModel.getUserId();
        UserBase userBase = userAtomSvc.selectBaseUserById(userId);
        if (StringUtils.isBlank(userBase.getEmail()) && !userBase.getEmail().equals(oldEmail)) {
            return resultFailed("原邮箱地址与系统记录不匹配，请刷新页面后重试");
        }
        if (oldEmail.equals(nowEmail)) {
            return resultFailed("新邮箱地址与原邮箱地址相同，不用修改");
        }
        if (StringUtils.isBlank(oldEmail) || SendCodeUtil.VALIDATE_CODE(KeyPrefix.REST, oldEmail, oldVerify)) {
            if (!SendCodeUtil.VALIDATE_CODE(KeyPrefix.REST, nowEmail, nowVerify)) {
                return resultFailed("新邮箱验证码错误");
            }
        } else {
            return resultFailed("原邮箱验证码错误");
        }
        UserBaseInput userBaseInput = new UserBaseInput();
        userBaseInput.setUserId(userId);
        userBaseInput.setEmail(nowEmail);
        return userAtomSvc.updateBaseUser(userBaseInput);
    }

    @Override
    public ServiceBean validateIdCard(RestModel restModel) {
        Integer userId = restModel.getUserId();
        String name = restModel.getName();
        String idCard = restModel.getIdCard();
        String phone = restModel.getPhone();
        String nowVerify = restModel.getNowVerify();
        UserBase userBase = userAtomSvc.selectBaseUserById(userId);
        if (StringUtils.isBlank(userBase.getPhone()) && !userBase.getPhone().equals(phone)) {
            return resultFailed("当前手机号与系统绑定手机号不一致，刷新后重试");
        }
        if (!SendCodeUtil.VALIDATE_CODE(KeyPrefix.REST, phone, nowVerify)) {
            return resultFailed("验证码错误");
        }
        ServiceBean serviceBean = SendCodeUtil.VALIDATE_IDCARD(idCard, phone, name);
        if (serviceBean.isSuccess()) {
            UserBaseInput userBaseInput = new UserBaseInput();
            userBaseInput.setUserId(userBase.getUserId());
            if (StringUtils.isBlank(userBase.getPhone())) {
                userBaseInput.setPhone(phone);
            }
            userBaseInput.setIdcard(idCard);
            userBaseInput.setTruename(name);
            userBaseInput.setStatus(UserState.AUTHEN.value());
            return userAtomSvc.updateBaseUser(userBaseInput);
        }
        return serviceBean;
    }

    @Override
    public ServiceBean<UserBaseOutput> qryUserBaseById(Integer userId) {
        UserBase userBase = userAtomSvc.selectBaseUserById(userId);
        return resultData(userBase);
    }

    @Override
    public ServiceBean<String> qryUserPhone(Integer userId) {
        UserBase userBase = userAtomSvc.selectBaseUserById(userId);
        return resultData(userBase.getPhone());
    }

    @Override
    public ServiceBean<String> qryUserEmail(Integer userId) {
        UserBase userBase = userAtomSvc.selectBaseUserById(userId);
        return resultData(userBase.getEmail());
    }

    @Override
    public ServiceBean hasPassword(Integer userId, Integer type) {
        String pwd = null;
        switch (type) {
            case 1:
                UserBase userBase = userAtomSvc.selectBaseUserById(userId);
                pwd = userBase.getPassword();
                break;
            case 2:
                UserPay userPay = userPayAtomSvc.selectUserPay(userId).getData();
                pwd = userPay.getPayPwd();
                break;
        }
        return resultData(pwd);
    }

    @Override
    public ServiceBean<UserPay> qryUserPayByUserId(Integer userId) {
        UserPay userPay = userPayAtomSvc.selectUserPay(userId).getData();
        return resultData(userPay);
    }

    @Override
    public ServiceBean<String> validatePayPwd(Integer userId, String pwd) {
        String key = "validate_pay_pwd_"+userId;
        int n = 0;
        boolean exists=redisUtil.exists(key);
        if (exists){
            String num = redisUtil.get(key);
            n = Integer.valueOf(num);
            if (n>=3){
                return resultFailed("错误次数超过三次，账户已锁定五小时");
            }
        }
        UserPay userPay = userPayAtomSvc.selectUserPay(userId).getData();
        if (StringUtils.isBlank(userPay.getPayPwd())){
            return resultFailed("NOT_PWD");
        }
        if (userPay.getPayPwd().equals(pwd)){
            if (exists){
                redisUtil.del(key);
            }
            return resultSuccess();
        }
        n++;
        if (n>=3){
            redisUtil.set(key,n+"",60*60*5);
        }else{
            redisUtil.set(key,n+"",60*60*1);
        }
        return resultFailed("支付密码错误,当前已错误"+n+"次，错误超过3次将锁定账号5个小时！");
    }

    @Override
    public ServiceBean<Map<String,Object>> qryUserSecurity(Integer userId) {
        UserBase userBase = userAtomSvc.selectBaseUserById(userId);
        UserPay userPay = userPayAtomSvc.selectUserPay(userId).getData();
        Map<String,Object> map = new HashMap<>();
        map.put("payPwd",StringUtils.isNotBlank(userPay.getPayPwd()));
        map.put("phone",StringUtils.isNotBlank(userBase.getPhone())?userBase.getPhone():null);
        map.put("email",StringUtils.isNotBlank(userBase.getEmail())?userBase.getEmail():null);
        map.put("authen",StringUtils.isNotBlank(userBase.getIdcard()));
        return resultData(map);
    }
}
